package com.warmlight.voicepacket.ui.user.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;
import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.adapter.MyCoverListOnNetAdapter;
import com.warmlight.voicepacket.base.BaseFragment;
import com.warmlight.voicepacket.data.UserCenterData;
import com.warmlight.voicepacket.http.Callback;
import com.warmlight.voicepacket.http.HttpClient;
import com.warmlight.voicepacket.http.HttpConfig;
import com.warmlight.voicepacket.utils.JSONUtils;
import com.warmlight.voicepacket.utils.MobClickHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;

import okhttp3.Call;

import static com.warmlight.voicepacket.db.VoicePacketDBHelper.LIST_ID;

public class OtherCoverFragment extends BaseFragment {

    private MyCoverListOnNetAdapter adapter;
    private ListView lv_my_playlist;
    private LinearLayout linearLayout;
    private String uid;
    private UserCenterData userCenterData;
    private TextView tv_no_cover;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my_cover, container, false);
        return view;
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        lv_my_playlist = view.findViewById(R.id.lv_my_playlist);
        tv_no_cover = view.findViewById(R.id.tv_no_cover);
        Bundle bundle = getArguments();
        uid = bundle.getString("uid");
        initView();
        initData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    private void initData() {
            adapter = new MyCoverListOnNetAdapter(getContext(), new ArrayList<UserCenterData.ListBean>(),true);
            lv_my_playlist.setAdapter(adapter);
            lv_my_playlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                    if (position == 0) {
                        return;
                    }
                    position--;
                    String audio_num = adapter.getItem(position).getAudio_num();
                    int num = Integer.valueOf(audio_num);
                    if (num > 0) {
                        Intent intent = new Intent(getContext(), OtherPlayDetailAcitivity.class);
                        intent.putExtra(LIST_ID,  adapter.getItem(position).getId());
                        intent.putExtra("type","other");
                        intent.putExtra("uid",uid);
                        if (userCenterData != null){
                            intent.putExtra("nickname",userCenterData.getAuthor().getNickname());
                        }
                        MobclickAgent.onEvent(getContext(), MobClickHelper.GSTATE_CLOT_INBAG,uid+"-"+adapter.getItem(position).getName());
                        getContext().startActivity(intent);
                    }

                }
            });
            loadData();
    }

    private void loadData() {
        String url = HttpConfig.USER_COVER;
        TreeMap<String, String> treeMap = new TreeMap<>();
        treeMap.put("uid", uid);
        HttpClient.post(url, treeMap, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, String response) {
//                String s = response.body().string();
                ArrayList<Map<String, String>> listMapByJson = JSONUtils.getListMapByJson(response);
                if (listMapByJson.size() > 0) {
                    Map<String, String> map = listMapByJson.get(0);
                    if (TextUtils.equals("200", map.get("code"))) {
                        String data = map.get("data");

                        userCenterData = new Gson().fromJson(data, UserCenterData.class);
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                initData((ArrayList<UserCenterData.ListBean>) userCenterData.getList());
                            }
                        });


//                        ArrayList<Map<String, String>> dataList = JSONUtils.getListMapByJson(data);
//                        Map<String, String> dataMap = dataList.get(0);
//                        String author = dataMap.get("author");
//                        String list = dataMap.get("list");
                    } else {
//                        SPUtils.clearLogin();
//                        getActivity().runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                initData();
//                            }
//                        });
                    }
                }
            }
        });
    }





    private void initView() {
        linearLayout = new LinearLayout(getContext());
        AbsListView.LayoutParams lp = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.setLayoutParams(lp);
        lv_my_playlist.addHeaderView(linearLayout);
    }

    private void headView(final UserCenterData.ListBean data) {
        linearLayout.removeAllViews();
        ImageView iv_myplaylist;
        ImageView iv_myplaylist_edit;
        TextView tv_myplaylist_title;
        TextView tv_myplaylist_count;
        ImageView iv_cover;
        View convertView = LayoutInflater.from(getContext()).inflate(R.layout.fragment_my_cover_header, null);
        tv_myplaylist_title = (TextView) convertView.findViewById(R.id.tv_myplaylist_title);
        tv_myplaylist_count = (TextView) convertView.findViewById(R.id.tv_myplaylist_count);
        iv_myplaylist_edit = (ImageView) convertView.findViewById(R.id.iv_myplaylist_edit);
        iv_myplaylist = (ImageView) convertView.findViewById(R.id.iv_myplaylist);
        iv_cover = (ImageView) convertView.findViewById(R.id.iv_cover);

//        final UserCenterData.ListBean data = list.get(0);
        if (data != null) {
            tv_myplaylist_title.setText(data.getName());
            tv_myplaylist_count.setText(data.getAudio_num() + "个");
            if ("我的最爱".equals(data.getName())) {
                iv_cover.setVisibility(View.VISIBLE);
            } else {
                iv_cover.setVisibility(View.GONE);
            }

            String avator = data.getAvator();
            RequestOptions options = new RequestOptions();
            options.placeholder(R.drawable.icon_iv_fail);
            Glide.with(getContext()).asBitmap().load(avator).apply(options).into(iv_myplaylist);
//        if("0".equals(data.getAudio_num())){
//            Glide.with(mContext).load(R.drawable.icon_iv_fail).asBitmap().dontAnimate().into(holder.iv_myplaylist);
//        }else{
////            List<DBFloatPlayListDetail> listAudios = DBHelper.getInstance(mContext).queryAudiosByListId(data.get_id());
//            List<DBFloatPlayListDetail> listAudios =  DBFloatPlayListDetailDaoHelp.queryBuilder(mContext,data.getId()+"");
//            if(listAudios!=null && listAudios.size()>0){
//                String url = listAudios.get(0).getAudio_ps();
//                Glide.with(mContext).load(TextUtils.isEmpty(url) ? R.drawable.icon_iv_fail : url).asBitmap().dontAnimate().into(holder.iv_myplaylist);
//            }else {
//                Glide.with(mContext).load(R.drawable.icon_iv_fail).asBitmap().dontAnimate().into(holder.iv_myplaylist);
//            }
//
//        }

            //如果播单名字是"我的最爱"则隐藏"更多"点点点按钮
            if ("我的最爱".equals(data.getName().trim())) {
                iv_myplaylist_edit.setVisibility(View.INVISIBLE);
            } else {
                iv_myplaylist_edit.setVisibility(View.VISIBLE);
            }

//            iv_myplaylist_edit.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    Intent intent = new Intent(getContext(), MyPlaylistEditActivity.class);
//                    Bundle bundle = new Bundle();
//                    bundle.putSerializable("cover_net", data);
//                    intent.putExtras(bundle);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    startActivity(intent);
//                }
//            });

            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String audio_num = data.getAudio_num();
                    int num = Integer.valueOf(audio_num);
                    if (num > 0) {

                        Intent intent = new Intent(getContext(), OtherPlayDetailAcitivity.class);
                        intent.putExtra(LIST_ID,  data.getId());
                        intent.putExtra("type","other");
                        intent.putExtra("uid",uid);
                        if (userCenterData != null){
                            intent.putExtra("nickname",userCenterData.getAuthor().getNickname());
                        }
//                        startActivity(intent);

//                        Intent intent = new Intent(getContext(), MyCoverDetailOnNetActivity.class);
////                    Bundle bundle = new Bundle();
////                    bundle.putSerializable(LOCAL,(DBFloatPlaylist)mPlaylist.get(position));
////                    intent.putExtras(bundle);
//                        intent.putExtra("cover_id", adapter.getItem(position).getId());
//                        intent.putExtra("is_other","1");
                        //我的播单点击
//                    MobclickAgent.onEvent(getActivity().getApplicationContext(), MobClickHelper.CLOT_FEED,mPlaylist.get(position).getList_name());
//                    HashMap<String,Object> temp = new HashMap<>();
//                    temp.put("我的播单点击",mPlaylist.get(position).getList_name().toString());
//                    ZhugeSDK.getInstance().track(getActivity().getApplicationContext(),MobClickHelper.CLOT_FEED,temp);

                        getContext().startActivity(intent);

//                        Intent intent = new Intent(getContext(), MyCoverDetailOnNetActivity.class);
////                    Bundle bundle = new Bundle();
////                    bundle.putSerializable(LOCAL,(DBFloatPlaylist)mPlaylist.get(position));
////                    intent.putExtras(bundle);
//                        intent.putExtra("cover_id", data.getId());
//                        intent.putExtra("is_other","1");
//                        //我的播单点击
////                    MobclickAgent.onEvent(getActivity().getApplicationContext(), MobClickHelper.CLOT_FEED,mPlaylist.get(position).getList_name());
////                    HashMap<String,Object> temp = new HashMap<>();
////                    temp.put("我的播单点击",mPlaylist.get(position).getList_name().toString());
////                    ZhugeSDK.getInstance().track(getActivity().getApplicationContext(),MobClickHelper.CLOT_FEED,temp);
//
//                        getContext().startActivity(intent);
                    }
                }
            });

            ImageView iv_add_cover = convertView.findViewById(R.id.iv_add_cover);
            iv_add_cover.setVisibility(View.GONE);
//            iv_add_cover.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    //我的播单创建
//                    MobclickAgent.onEvent(getActivity().getApplicationContext(), MobClickHelper.CLOT_BUILD);
//                    ZhugeSDK.getInstance().track(getActivity().getApplicationContext(), MobClickHelper.CLOT_BUILD);
//
//                    getActivity().startActivity(new Intent(getActivity(), CreateNetPlaylistActivity.class));
//                }
//            });
            linearLayout.addView(convertView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        }
    }


    private void initData(ArrayList<UserCenterData.ListBean> data) {
        UserCenterData.ListBean dd = null;
        for (int i = 0; i < data.size(); i++) {
            UserCenterData.ListBean listBean = data.get(i);
            if (TextUtils.equals("我的最爱", listBean.getName())) {
                dd = listBean;
                data.remove(i);
                break;
            }
        }

        headView(dd);
        adapter.setList(data);
        if (data.size() == 0){
            tv_no_cover.setVisibility(View.VISIBLE);
        }

    }


}
